package example.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;


import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

/**
 * @author ZhangXianChao
 */

@Configuration
@EnableTransactionManagement
@PropertySource(value = "classpath:application.yml", ignoreResourceNotFound = true)
public class MybatisConfig implements TransactionManagementConfigurer {

    @Value("${mybatis.mapper-locations}")
    private String mapper;

    @Value("${mybatis.type-aliases-package}")
    private String aliases;

    @Resource
    private DataSource dataSource;

    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        // 设置数据源
        bean.setDataSource(dataSource);
        // 设置xml
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapper));
        // 设置别名
        bean.setTypeAliasesPackage(aliases);
        // 添加分页插件
        bean.setPlugins(new Interceptor[]{pageInterceptor()});
        bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return bean.getObject();
    }

    /**
     * 分页拦截器
     * @return
     */
    private PageInterceptor pageInterceptor() {
        PageInterceptor pageInterceptor = new PageInterceptor();
        // 详见 com.github.pageHelper.page.PageParams
        Properties p = new Properties();
        // RowBounds是否进行count查询 - 默认不查询
        p.setProperty("rowBoundsWithCount", "true");
        // 当设置为true的时候，如果page size设置为0（或RowBounds的limit=0），就不执行分页，返回全部结果
        p.setProperty("pageSizeZero", "true");
        // 分页合理化
        p.setProperty("reasonable", "false");
        // 是否支持接口参数来传递分页参数，默认false
        p.setProperty("supportMethodsArguments", "true");
        // 设置数据库方言 ， 也可以不设置，会动态获取
        p.setProperty("helperDialect", "mysql");
        pageInterceptor.setProperties(p);
        return pageInterceptor;
    }

    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}
